//
//  HotTopicsViewController.m
//  GiftThat
//
//  Created by ChuXiang on 16/1/6.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "HotTopicsViewController.h"
#import "LJFHotCollectionViewCell.h"
#import "LJFModel.h"
#import "LJFNewHotViewController.h"
#import <MJRefresh.h>
#import "LJFSearchViewController.h"
@interface HotTopicsViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *muArray;
@property (nonatomic,copy) NSString *nextPageUrl;
@end

@implementation HotTopicsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = self.collectionView.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
    
    self.navigationItem.backBarButtonItem.tintColor = [UIColor whiteColor];

    self.navigationItem.title = @"热门";

    self.muArray = [NSMutableArray array];
    
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(searchButtonDid)];
    self.navigationItem.rightBarButtonItem = searchItem;
    
    [self getUrl:kHotTopicsURL];
    [self creatCollectionView];
    
#pragma mark-新的mjrefresh加载动图用法
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(headDid)];
        NSMutableArray *muArray = [NSMutableArray array];
        for (NSUInteger i = 1;i <= 5 ; i++) {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"box_0%zd",i]];
            [muArray addObject:image];
        }
    
        [header setImages:muArray forState:MJRefreshStateRefreshing];
        self.collectionView.mj_header = header;

}

-(void)searchButtonDid{
    
    LJFSearchViewController *searchController = [[LJFSearchViewController alloc]init];
    [self.navigationController pushViewController:searchController animated:YES];
}

//网络请求
-(void)getUrl:(NSString *)url{
    if ([url isEqual:[NSNull null]]) {
        [self.collectionView.mj_footer endRefreshing];
    }else{
    [CXNetWorkTool getWithUrl:url parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        
        NSDictionary *dic = result;
        NSDictionary *dic1 = [dic objectForKey:@"data"];
        NSArray *array = [dic1 objectForKey:@"items"];
//        获取下一页的url
        NSDictionary *dic2 = [[NSDictionary alloc]initWithDictionary:[dic1 objectForKey:@"paging"]];
        self.nextPageUrl  = [dic2 objectForKey:@"next_url"];
        
        for (NSDictionary *dic2 in array) {
            LJFModel *hot = [[LJFModel alloc]initWithDictionary:[dic2 objectForKey:@"data"]];

            [self.muArray addObject:hot];
        }
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    }
}
//collectionview的创建
-(void)creatCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = CGFLOAT_MIN;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.itemSize = CGSizeMake((self.view.frame.size.width - 10)/2,200);
    
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(5, 0, self.view.frame.size.width - 10, self.view.frame.size.height - 113) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[LJFHotCollectionViewCell class] forCellWithReuseIdentifier:@"NewCollectionViewCell"];
//    collectionview的上拉加载
    
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footDid)];
    
    [self.view addSubview:self.collectionView];
    
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    LJFHotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NewCollectionViewCell" forIndexPath:indexPath];
        if (self.muArray.count > indexPath.item) {
        cell.ljfmodel = self.muArray[indexPath.item];
    }
    return cell;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.muArray.count;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    LJFModel *model = [[LJFModel alloc]init];
    if (self.muArray.count > indexPath.item) {
        model = self.muArray[indexPath.item];
        LJFNewHotViewController *new = [[LJFNewHotViewController alloc]init];
        new.ljfmodel = self.muArray[indexPath.item];
        new.urlString = new.ljfmodel.url;
        [self.navigationController pushViewController:new
                                             animated:YES];
    }
}
#pragma mark-下拉刷新的方法
-(void)headDid{
    [self.muArray removeAllObjects];
    [self getUrl:kHotTopicsURL];
//        延迟两秒停止刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.collectionView.mj_header endRefreshing];
        
    });
    
    
}
#pragma mark-上拉加载的方法
-(void)footDid{

    [self getUrl:self.nextPageUrl];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
